package it.rockliveitalia.tool;

import it.rockliveitalia.R;
import it.rockliveitalia.entity.Event;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;

public class Sender {

	private static final String URLF = "http://rockliveitalia.xoom.it/databaseFile/";
	private String fileName;

	public List<File> createFile(Activity a, Date date, boolean firstTime) {
		List<File> fileList = new ArrayList<File>();
		if (firstTime) {
			Calendar cal = Calendar.getInstance();
			Event e = new Event();
			e.setDate(a.getString(R.string.initial_date));
			cal.setTime(e.getDate());
			fileName = cal.get(Calendar.DATE) + "_"
					+ (cal.get(Calendar.MONTH) + 1) + "_"
					+ cal.get(Calendar.YEAR) + ".xml";
		} else {
			Calendar today = Calendar.getInstance();
			Calendar cal = Calendar.getInstance();
			cal.clear();
			cal.setTime(date);
			if (today.get(Calendar.YEAR) == cal.get(Calendar.YEAR)
					&& today.get(Calendar.DAY_OF_YEAR) == cal
							.get(Calendar.DAY_OF_YEAR)) {
				fileName = today.get(Calendar.DATE) + "_"
						+ (today.get(Calendar.MONTH) + 1) + "_"
						+ today.get(Calendar.YEAR) + ".xml";
			} else {
				cal.set(Calendar.DATE, cal.get(Calendar.DATE) + 1);
				fileName = cal.get(Calendar.DATE) + "_"
						+ (cal.get(Calendar.MONTH) + 1) + "_"
						+ cal.get(Calendar.YEAR) + ".xml";
			}

		}
		do {
			File root = a.getFilesDir();
			File file = new File(root, fileName);
			fileList.add(file);
		} while (nextFile(date, firstTime));

		return fileList;
	}

	private boolean nextFile(Date date, boolean firstTime) {
		Calendar cal3 = Calendar.getInstance();
		cal3.set(Calendar.HOUR_OF_DAY, 23);
		cal3.set(Calendar.MINUTE, 59);
		Calendar cal2 = Calendar.getInstance();
		Event e = new Event();
		e.setDate(computeDate(fileName));
		cal2.setTime(e.getDate());
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date);
		cal1.set(Calendar.HOUR_OF_DAY, 0);
		cal1.set(Calendar.MINUTE, 1);
		if (!firstTime) {
			if (cal2.getTimeInMillis() > cal1.getTimeInMillis()) {
				if (cal2.get(Calendar.YEAR) != cal3.get(Calendar.YEAR)
						|| cal2.get(Calendar.DAY_OF_YEAR) != cal3
								.get(Calendar.DAY_OF_YEAR)) {
					cal2.set(Calendar.DATE, cal2.get(Calendar.DATE) + 1);
					fileName = cal2.get(Calendar.DATE) + "_"
							+ (cal2.get(Calendar.MONTH) + 1) + "_"
							+ cal2.get(Calendar.YEAR) + ".xml";
					return true;
				}
			}
		}
		return false;
	}

	public String computeDate(String fileN) {
		int i = 0;
		int temp = 0;
		i = fileN.indexOf("_", i + 1);
		String day = fileN.substring(temp, i);
		temp = i + 1;
		i = fileN.indexOf("_", i + 1);
		String month = fileN.substring(temp, i);
		temp = i + 1;
		i = fileN.indexOf(".", i + 1);
		String year = fileN.substring(temp, i);
		return day + "/" + month + "/" + year;
	}

	public String download(List<File> fileList, Date date) {

		int i = 0;
		String result = null;
		boolean noConnection = false;
		do {
			try {
				fileName = fileList.get(i).getName();
				URL url = new URL(URLF + fileName); // you can
													// write
													// here
													// any
				// link

				/* Open a connection to that URL. */
				URLConnection ucon = url.openConnection();
				ucon.setConnectTimeout(15000);
				ucon.setReadTimeout(60000);

				/*
				 * Define InputStreams to read from the URLConnection.
				 */
				InputStream is = ucon.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);

				/*
				 * Read bytes to the Buffer until there is nothing more to
				 * read(-1).
				 */
				ByteArrayBuffer baf = new ByteArrayBuffer(5000);
				int current = 0;
				while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}
				FileOutputStream fos = new FileOutputStream(fileList.get(i));
				fos.write(baf.toByteArray());
				fos.flush();
				fos.close();
				result = fileName;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				result = "todayFile";
			} catch (UnknownHostException e) {
				e.printStackTrace();
				result = "NoConnection";
				noConnection = true;
			} catch (SocketTimeoutException e) {
				e.printStackTrace();
				result = "NoConnection";
				noConnection = true;
			} catch (IOException e) {
				e.printStackTrace();
			}
			i++;

		} while (i < fileList.size() && !noConnection);

		if (result != null)
			if (!result.equals("NoConnection") && !result.equals("todayFile"))
				return computeDate(result);
		return result;
	}

}
